#!/bin/bash -e

case "$1" in
    configure)

        # Default values, in case debconf was not used to set them.  These will
        # be used for system configurations down below after debconf values are
        # read.
        # NOTE: make sure to match these defaults with the rivendell.postrm script
        AUDIOUSER="rduser"
        AUDIOGROUP="rivendell"
        AUDIOROOT="/var/snd"
        REMOVEDATA="false"


        # create configuration file, based on debconf entries
        . /usr/share/debconf/confmodule

        # Is the user configuring with debconf?
        db_get rivendell/debconfenable
        if [ "$RET" = "true" ]; then

            # generate the rd.conf file from debconf settings.
            dc="/etc/rd.conf"
            if [ -e "$dc" ]; then
                cp -a "$dc" "${dc}.dpkg-save"
            fi

            echo "; NOTE: this file was generated by the rivendell debian package" > "$dc"
            echo ";" >> "$dc"
            echo "; DO NOT EDIT THIS FILE!  Your changes will be lost on the next upgrade." >> "$dc"
            echo ";" >> "$dc"
            echo "; To regenerate this file (or to select manual configuration) run the command:" >> "$dc"
            echo ";     dpkg-reconfigure rivendell" >> "$dc"
            echo ";"
            echo "" >> "$dc"

            echo "[Identity]" >> "$dc"
            db_get rivendell/identity/password
            echo "Password=$RET" >> "$dc"
            db_get rivendell/identity/audioowner
            echo "AudioOwner=$RET" >> "$dc"
            AUDIOUSER="$RET"
            db_get rivendell/identity/audiogroup
            echo "AudioGroup=$RET" >> "$dc"
            AUDIOGROUP="$RET"
            echo "" >> "$dc"

            echo "[Format]" >> "$dc"
            db_get rivendell/format/samplerate
            echo "SampleRate=$RET" >> "$dc"
            db_get rivendell/format/channels
            echo "Channels=$RET" >> "$dc"
            echo "" >> "$dc"

            echo "[mySQL]" >> "$dc"
            db_get rivendell/mysql/hostname
            echo "Hostname=$RET" >> "$dc"
            db_get rivendell/mysql/loginname
            echo "Loginname=$RET" >> "$dc"
            db_get rivendell/mysql/password
            echo "Password=$RET" >> "$dc"
            db_get rivendell/mysql/database
            echo "Database=$RET" >> "$dc"
            db_get rivendell/mysql/driver
            echo "Driver=$RET" >> "$dc"
            echo "" >> "$dc"

            echo "[Cae]" >> "$dc"
            db_get rivendell/cae/audioroot
            echo "AudioRoot=$RET" >> "$dc"
            AUDIOROOT="$RET"
            db_get rivendell/cae/audioextension
            echo "AudioExtension=$RET" >> "$dc"
            db_get rivendell/cae/allownonstandardrates
            echo "AllowNonstandardRates=$RET" >> "$dc"
            echo "" >> "$dc"

            echo "[Tuning]" >> "$dc"
            db_get rivendell/tuning/userealtime
            echo "UseRealtime=$RET" >> "$dc"
            echo "" >> "$dc"

            echo ";" >> "$dc"
            echo "; Log Generation, mainly useful for debugging" >> "$dc"
            echo ";" >> "$dc"
            echo "" >> "$dc"
            echo "[RDAirPlay]" >> "$dc"
            db_get rivendell/rdairplay/logfile
            echo "Logfile=$RET" >> "$dc"
            echo "" >> "$dc"
            echo "[RDCatchd]" >> "$dc"
            db_get rivendell/rdcatchd/logfile
            echo "Logfile=$RET" >> "$dc"
            echo "" >> "$dc"
            echo "[Ripcd]" >> "$dc"
            db_get rivendell/ripcd/logfile
            echo "Logfile=$RET" >> "$dc"
            echo "" >> "$dc"
            echo "[Caed]" >> "$dc"
            db_get rivendell/caed/logfile
            echo "Logfile=$RET" >> "$dc"
            echo "" >> "$dc"

            db_get rivendell/audioadapters/selections
            JACK_CARD=0 # initialize JACK card to 0

            # no configuration needed for HPI, simply increment JACK card
            if  echo "$RET" | grep -s "Audioscience HPI" &> /dev/null ; then
                let JACK_CARD=$JACK_CARD+1
            fi

            # no configuration needed for ALSA, simply increment JACK card
            if  echo "$RET" | grep -s "ALSA" &> /dev/null ; then
                let JACK_CARD=$JACK_CARD+1
            fi

            # JACK configuration file portion
            if  echo "$RET" | grep -s "JACK" &> /dev/null ; then
                cat >> "$dc" << EOF 
;
; JACK Session Management
;
;  See the 'JACK.txt' file for details on how this works!
;
[JackSession]
Source1=rivendell_${JACK_CARD}:playout_0L
Destination1=alsa_pcm:playback_1

Source2=rivendell_${JACK_CARD}:playout_0R
Destination2=alsa_pcm:playback_2

Source3=rivendell_${JACK_CARD}:playout_1L
Destination3=alsa_pcm:playback_1

Source4=rivendell_${JACK_CARD}:playout_1R
Destination4=alsa_pcm:playback_2

Source5=rivendell_${JACK_CARD}:playout_2L
Destination5=alsa_pcm:playback_1

Source6=rivendell_${JACK_CARD}:playout_2R
Destination6=alsa_pcm:playback_2

Source7=rivendell_${JACK_CARD}:playout_3L
Destination7=alsa_pcm:playback_1

Source8=rivendell_${JACK_CARD}:playout_3R
Destination8=alsa_pcm:playback_2

Source9=rivendell_${JACK_CARD}:playout_4L
Destination9=alsa_pcm:playback_1

Source10=rivendell_${JACK_CARD}:playout_4R
Destination10=alsa_pcm:playback_2

Source11=rivendell_${JACK_CARD}:playout_5L
Destination11=alsa_pcm:playback_1

Source12=rivendell_${JACK_CARD}:playout_5R
Destination12=alsa_pcm:playback_2

Source13=rivendell_${JACK_CARD}:playout_6L
Destination13=alsa_pcm:playback_1

Source14=rivendell_${JACK_CARD}:playout_6R
Destination14=alsa_pcm:playback_2

Source15=rivendell_${JACK_CARD}:playout_7L
Destination15=alsa_pcm:playback_1

Source16=rivendell_${JACK_CARD}:playout_7R
Destination16=alsa_pcm:playback_2

Source17=alsa_pcm:capture_1
Destination17=rivendell_${JACK_CARD}:record_0L

Source18=alsa_pcm:capture_2
Destination18=rivendell_${JACK_CARD}:record_0R
EOF

                # generate global /etc/jackdrc configuration file
                dc="/etc/jackdrc"
                if [ -e "$dc" ]; then
                    cp -a "$dc" "${dc}.dpkg-save"
                fi
                db_get rivendell/format/samplerate
                echo "/usr/bin/jackd --realtime --temporary --driver alsa --rate $RET" > "$dc"
                # FIXME: unfortunately jackd cannot parse comments, so none can be added at this time to /etc/jackdrc

                # generate global X11 Xsession.d configuration file to set JACK_START_SERVER environment variable
                dc="/etc/X11/Xsession.d/98jack-environment"
                if [ -e "$dc" ]; then
                    cp -a "$dc" "${dc}.dpkg-save"
                fi
                echo "# NOTE: this file was generated by the rivendell debian package" > "$dc"
                echo "#" >> "$dc"
                echo "# DO NOT EDIT THIS FILE!  Your changes will be lost on the next upgrade." >> "$dc"
                echo "#" >> "$dc"
                echo "# To regenerate this file (or to select manual configuration) run the command:" >> "$dc"
                echo "#     dpkg-reconfigure rivendell" >> "$dc"
                echo "" >> "$dc"
                echo "# set environment variable for JACK to start if not running" >> "$dc"
                echo "# (NOTE: /etc/jackdrc is read for the jackd command line)." >> "$dc"
                echo "export JACK_START_SERVER=1" >> "$dc"
            fi  # End of if rivendell/audioadapters/selections has JACK
            # End of generate the rd.conf file from debconf settings.

            # generate init script configuration file from debconf settings.
            dc="/etc/default/rivendell"
            if [ -e "$dc" ]; then
                cp -a "$dc" "${dc}.dpkg-save"
            fi
            echo "# Defaults for rivendell initscript." > "$dc"
            echo "# Sourced by /etc/init.d/rivendell ." >> "$dc"
            echo "# NOTE: this file was generated by the rivendell debian package." >> "$dc"
            echo "#" >> "$dc"
            echo "# To regenerate this file (or to select manual configuration) run the command:" >> "$dc"
            echo "#     dpkg-reconfigure rivendell" >> "$dc"
            echo "#" >> "$dc"
            echo "# This is a POSIX shell fragment." >> "$dc"
            echo "#" >> "$dc"
            echo "" >> "$dc"
            echo "# How should Rivendell daemons (caed, ripcd, rdcatchd) run?" >> "$dc"
            echo "# Possible values are 'init.d' or 'pam_rd'." >> "$dc"
            db_get rivendell/run_mode || true
            echo "RUN_MODE=\"$RET\" " >> "$dc"

            # populate PAM scripts with pam_rd hooks if requested by the user and it is not already in there
            # FIXME: this is currently hard-coded to work with the kdm PAM script, but should ideally be more flexible.
            db_get rivendell/run_mode
            if [ "$RET" = "pam_rd" ]; then
                dc="/etc/pam.d/kdm"

                if [ `grep --count "pam_rd.so" "$dc"` -eq 0 ] ; then
                    cp -a "$dc" "${dc}.dpkg-save"

                    # sed command to 
                    # replace (substitute):
                    #   @include common-auth
                    # with
                    #   auth       optional     pam_rd.so   debug kill_rd_daemons destroy_shm ignore_pass \\
                    #   @include common-auth
                    # note only 1 backslash after first line, as we don't want an extra blank line in the output file.
                    sed -e "s/^[[:space:]]*@include common-auth[[:space:]]*/\
auth       optional     pam_rd.so   debug kill_rd_daemons destroy_shm ignore_pass \\
@include common-auth/" \
                        < ${dc} >${dc}.dpkg-tmp
                    mv -f ${dc}.dpkg-tmp ${dc}
                fi
            fi # End of populate PAM scripts.

        fi # End of if rivendell/debconfenable = true

        db_stop # End of debconf section


        # Do other system configurations, using debconf values if set, and
        # falling back to defaults if not using debconf.

        # create Rivendell user and group
        if ! getent group "$AUDIOGROUP" >/dev/null; then
            # Adding system group:
            addgroup --system "$AUDIOGROUP" 2> /dev/null || true
        fi
        if ! getent passwd "$AUDIOUSER" >/dev/null; then
            # Adding system user:
            adduser \
              --system \
              --group \
              --home $AUDIOROOT \
              --no-create-home \
              --shell /bin/bash \
              --gecos "Rivendell system account" \
              $AUDIOUSER  >/dev/null
        fi
        if ! getent group "$AUDIOGROUP" | grep -q "$AUDIOUSER"; then
            # Add the user to the group
            adduser $AUDIOUSER $AUDIOGROUP
        fi


        # Create audio store directory and set permissions.
        if [ ! -d "$AUDIOROOT" ]; then
            install --directory --mode 02775 --owner="$AUDIOUSER" --group="$AUDIOGROUP" "$AUDIOROOT"
        fi

        # Create run directory to store pid files .
        if [ ! -d /var/run/rivendell ]; then
            install --directory --mode 02775 --owner="$AUDIOUSER" --group="$AUDIOGROUP" /var/run/rivendell
        fi

        # Create log directory to store log files .
        #FIXME: better integrate with debconf  (debconf currently only has various log file paths).
        if [ ! -d /var/log/rivendell ]; then
            install --directory --mode 02775 --owner="$AUDIOUSER" --group="$AUDIOGROUP" /var/log/rivendell
        fi
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
        echo "$0 called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

# dh_makeshlibs doesn't add it automaticaly (?!)
if [ "$1" = "configure" ]; then
        ldconfig
fi

#DEBHELPER#
